import { _login, _auth } from '../../common/api/signin'
const roles = [
  {
    name: '全民推荐',
    desc: '(非业主)',
    img: './b1.png'
  },
  {
    name: '业主推荐',
    desc: '(业主)',
    img: './b2.png'
  },
  {
    name: '置业顾问',
    img: './b3.png'
  },
  {
    name: '销售经理',
    img: './b4.png'
  }
]
const app = getApp()
Page({
  data: {
    roles
  },
  onGetUserInfo(e) {
    let { iv, encryptedData } = e.detail
    if (iv && encryptedData) {
      app.loading('加载中')
      const index = e.currentTarget.dataset.index
      const { roles } = this.data
      const role = roles[index].name
      wx.checkSession({
        success: () => {
          console.log('登录未过期')
          let session_key = wx.getStorageSync('session_key')
          _auth(session_key, iv, encryptedData).then(res => {
            if (res.data.IsSuccess) {
              wx.hideLoading()
              let uid = res.data.Data.unionId
              wx.setStorageSync('uid', uid)
              wx.navigateTo({
                url: `./index?type=${role}`
              })
            }
          }).catch(err => {
            wx.hideLoading()
            console.log(err)
          })
        },
        fail: () => {
          console.log('登录已过期，重新登录')
          wx.login({
            success: r => {
              _login(r.code).then(res => {
                if (res.data.IsSuccess) {
                  wx.setStorageSync('session_key', res.data.Data.session_key)
                  let session_key = wx.getStorageSync('session_key')
                  _auth(session_key, iv, encryptedData).then(res => {
                    if (res.data.IsSuccess) {
                      wx.hideLoading()
                      let uid = res.data.Data.unionId
                      wx.setStorageSync('uid', uid)
                      // wx.redirectTo({
                      //   url: '/pages/index/index'
                      // })
                      wx.navigateTo({
                        url: `./index?type=${role}`
                      })
                    }
                  }).catch(err => {
                    wx.hideLoading()
                    console.log(err)
                  })
                } else {
                  wx.hideLoading()
                  wx.showModal({
                    title: '对不起',
                    content: res.data.Data,
                    showCancel: false
                  })
                }
              }).catch(err => {
                wx.hideLoading()
                console.log(err)
              })
            }
          })
        }
      })
    } else {
      wx.hideLoading()
    }
  },
  onLoad(options) { },
  onReady() { },
  onShow() { },
  onShareAppMessage() {
    return app.shareInfo
  }
})